//
//  RequestHelper.m
//  MCF2
//
//  Created by QianDeng on 15/6/9.
//  Copyright (c) 2015年 ac. All rights reserved.
//

#import "RequestHelper.h"
#import "UserModel.h"
#import "RequestUtils.h"
#import "MBProgressHUD.h"
#import "UIDevice+Extension.h"

@implementation RequestHelper

//URL添加cookie
+ (void)addCookieWithUrl:(NSString *)url
{
    NSMutableArray *cookieList = [[NSMutableArray alloc] initWithCapacity:1];
    UserModel *userModel = [UserModel mj_objectWithKeyValues:getUserData()];
    if (userModel.Id) {
        NSString *paramsStr = [NSString stringWithFormat:@"m_mcuserid=%@",userModel.Id];
        NSMutableDictionary *cookieDict = [[NSMutableDictionary alloc] initWithCapacity:1];
        [cookieDict setObject:paramsStr forKey:@"Set-Cookie"];
        NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:cookieDict
                                                                          forURL:[NSURL URLWithString:url]];
        [cookieList addObjectsFromArray:headeringCookie];
    }
    
    if (getToken()) {
        NSString *paramsStr = [NSString stringWithFormat:@"m_mcsesssion=%@",getToken()];
        NSMutableDictionary *cookieDict = [[NSMutableDictionary alloc] initWithCapacity:1];
        [cookieDict setObject:paramsStr forKey:@"Set-Cookie"];
        NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:cookieDict
                                                                          forURL:[NSURL URLWithString:url]];
        [cookieList addObjectsFromArray:headeringCookie];
    }
    
    if (userModel.UserName) {
        NSString *paramsStr = [NSString stringWithFormat:@"m_mcusername=%@",userModel.UserName];
        NSMutableDictionary *cookieDict = [[NSMutableDictionary alloc] initWithCapacity:1];
        [cookieDict setObject:paramsStr forKey:@"Set-Cookie"];
        NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:cookieDict
                                                                          forURL:[NSURL URLWithString:url]];
        [cookieList addObjectsFromArray:headeringCookie];
    }
    
    if (userModel.CityId) {
        NSString *paramsStr = [NSString stringWithFormat:@"m_mccityid=%@",userModel.CityId];
        NSMutableDictionary *cookieDict = [[NSMutableDictionary alloc] initWithCapacity:1];
        [cookieDict setObject:paramsStr forKey:@"Set-Cookie"];
        NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:cookieDict
                                                                          forURL:[NSURL URLWithString:url]];
        [cookieList addObjectsFromArray:headeringCookie];
    }
    
    if (userModel.ShopId) {
        NSString *paramsStr = [NSString stringWithFormat:@"m_moihopid=%@",userModel.ShopId];
        NSMutableDictionary *cookieDict = [[NSMutableDictionary alloc] initWithCapacity:1];
        [cookieDict setObject:paramsStr forKey:@"Set-Cookie"];
        NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:cookieDict
                                                                          forURL:[NSURL URLWithString:url]];
        [cookieList addObjectsFromArray:headeringCookie];
    }
    
    if (cookieList) {
        
        // 通过setCookies方法，完成设置，这样只要一访问URL为HOST的网页时，会自动附带上设置好的header
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookieList
                                                           forURL:[NSURL URLWithString:url]
                                                  mainDocumentURL:nil];
    }
}

//生成HTTP请求的header参数
+ (NSMutableDictionary *)createRequestHeaderParams
{
    NSMutableDictionary * requestHeader = [NSMutableDictionary dictionaryWithCapacity:1];
    [requestHeader setObject:@"iOS_MOI" forKey:@"Channel"];
    [requestHeader setObject:@"" forKey:@"Culture"];
    [requestHeader setObject:@"" forKey:@"auth"];
    if (getToken()) {
        [requestHeader setObject:getToken() forKey:@"SessionId"];
    }
//    else{
//        [requestHeader setObject:@"" forKey:@"SessionId"];
//    }
    if ([UIDevice deviceIPAdress]) {
        [requestHeader setObject:[UIDevice deviceIPAdress] forKey:@"ClientIP"];
    }
    else
    {
        [requestHeader setObject:@"127.0.0.1" forKey:@"ClientIP"];
    }
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    if (version) {
        [requestHeader setObject:version forKey:@"Version"];
    }
    
    NSTimeInterval second = [[NSDate date] timeIntervalSince1970];
    NSNumber *stamp = [NSNumber numberWithInteger:second*1000];
    [requestHeader setObject:stamp forKey:@"Timestamp"];
    
    return requestHeader;
}

//拼接参数
+ (NSString *)createParamsString:(NSDictionary *)params
{
    if (!params) {
        return nil;
    }
    NSArray *keys = [params allKeys];
    //对KEY进行排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2){
        return [[obj1 uppercaseString] compare:[obj2 uppercaseString] options:NSNumericSearch];
        
    }];
    NSString *paramsString = nil;
    for (int i=0; i<sortedArray.count; i++) {
        NSString *keyStr = [sortedArray objectAtIndex:i];
        id value = [params objectForKey:keyStr];
        if ([value isKindOfClass:[NSString class]]) {
            
            if (((NSString *)value).length>0) {
                if (!paramsString) {
                    paramsString = [NSString stringWithFormat:@"%@=%@",[keyStr uppercaseString],value];
                }
                else{
                    paramsString = [NSString stringWithFormat:@"%@&%@=%@",paramsString,[keyStr uppercaseString],value];
                }
            }
        }
        else if([value isKindOfClass:[NSNumber class]])
        {
            if ([value intValue]!=0) {  //如果为0的参数过滤掉
                if (!paramsString) {
                    paramsString = [NSString stringWithFormat:@"%@=%@",[keyStr uppercaseString],value];
                }
                else{
                    paramsString = [NSString stringWithFormat:@"%@&%@=%@",paramsString,[keyStr uppercaseString],value];
                }
            }
        }
        else if([value isKindOfClass:[NSDate class]])
        {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *dateStr = [formatter stringFromDate:(NSDate *)value];
            if (!paramsString) {
                paramsString = [NSString stringWithFormat:@"%@=%@",[keyStr uppercaseString],dateStr];
            }
            else{
                paramsString = [NSString stringWithFormat:@"%@&%@=%@",paramsString,[keyStr uppercaseString],dateStr];
            }
        }
    }
    
    return paramsString;
}

+ (NSString *)createSiginCode:(NSString *)methodName withParams:(NSDictionary *)params withTimeStamp:(NSNumber *)stamp
{
    NSString *paramsString=[[self class] createParamsString:params];
    NSString *privateString=[NSString stringWithFormat:@"AppId=%@",IOSAppId];
    if (methodName) {
        privateString=[NSString stringWithFormat:@"%@&MethodName=%@",privateString,[methodName uppercaseString]];
    }
    if (paramsString) {
        privateString=[NSString stringWithFormat:@"%@&%@",privateString,paramsString];
    }
    privateString=[NSString stringWithFormat:@"%@&ClientSecret=%@",privateString,ClientSecret];
    if (stamp) {
        privateString=[NSString stringWithFormat:@"%@&Timestamp=%@",privateString,stamp];
    }
    
    NSLog(@"privateString=%@",privateString);
    NSString *md5Str = [md5(privateString) lowercaseString];
    
    return md5Str;
}

+ (NSString *)createMD5SiginCode:(NSString *)methodName withParams:(NSDictionary *)params
{
    NSMutableDictionary *hDict = [params objectForKey:@"requestHead"];
    NSDictionary *bDict = [params objectForKey:@"body"];
    
    NSString *paramsString=[[self class] createParamsString:bDict];
    NSNumber *stamp = [hDict objectForKey:@"Timestamp"];
    NSString *privateString=[NSString stringWithFormat:@"AppId=%@",IOSAppId];
    if (methodName) {
        privateString=[NSString stringWithFormat:@"%@&MethodName=%@",privateString,[methodName uppercaseString]];
    }
    if (paramsString) {
        privateString=[NSString stringWithFormat:@"%@&%@",privateString,paramsString];
    }
    privateString=[NSString stringWithFormat:@"%@&ClientSecret=%@",privateString,ClientSecret];
    if (stamp) {
        privateString=[NSString stringWithFormat:@"%@&Timestamp=%@",privateString,stamp];
    }
    
    NSLog(@"privateString=%@",privateString);
    
    NSString *md5Str = [md5(privateString) lowercaseString];
    
    return md5Str;
}

/*创建page属性参数
 *@param  index   页码
 *@param  size    个数
 *@param  direction
 */
+ (NSMutableDictionary *)createPagingSettingWithPageIndex:(NSInteger)index size:(NSInteger)size direction:(NSInteger)direction orderBy:(NSInteger)orderBy
{
    NSMutableDictionary * pageDict = [NSMutableDictionary dictionaryWithCapacity:1];
    [pageDict setObject:[NSNumber numberWithInteger:index] forKey:@"Index"];
    [pageDict setObject:[NSNumber numberWithInteger:size] forKey:@"Size"];
    [pageDict setObject:[NSNumber numberWithInteger:direction] forKey:@"Direction"];
    [pageDict setObject:[NSNumber numberWithInteger:orderBy] forKey:@"OrderBy"];
    
    return pageDict;
}

+ (NSMutableDictionary *)resovleRequestCallBack:(NSDictionary *)dict
{
    NSMutableDictionary *retDict = [[NSMutableDictionary alloc] initWithCapacity:1];
    if ([dict objectForKey:@"error"])
    {  //请求失败
        [retDict setObject:[NSNumber numberWithInt:ProtErr] forKey:@"ret"];
        [retDict setObject:@"网络异常，请稍后再试!" forKey:@"errorInfo"];
    }
    else
    {
        NSDictionary *dataDict = [dict objectForKey:@"data"];
        
        NSDictionary *statusDict = [dataDict objectForKey:@"ResponseStatus"];
        if ([statusDict objectForKey:@"Ack"] && [[statusDict objectForKey:@"Ack"] isEqualToString:@"Success"])
        {//成功
            NSDictionary *bodyDict = [dataDict objectForKey:@"Body"];
            [retDict setObject:[NSNumber numberWithInt:ProtSuc] forKey:@"ret"];
            if (bodyDict)
            {
                [retDict setObject:bodyDict forKey:@"data"];
            }
            //如果有结果状态返回，根据结果状态返回成功失败
            if ([bodyDict objectForKey:@"IsSuccess"] && ![[bodyDict objectForKey:@"IsSuccess"] boolValue]) {
                [retDict setObject:[NSNumber numberWithInt:ProtErr] forKey:@"ret"];
                if ([bodyDict objectForKey:@"Message"]) {
                    [retDict setObject:[bodyDict objectForKey:@"Message"] forKey:@"errorInfo"];
                }
            }
        }
        else
        {
            [retDict setObject:[NSNumber numberWithInt:ProtErr] forKey:@"ret"];
            NSArray *errors = [statusDict objectForKey:@"Errors"];
            if (errors.count>0) {
                NSDictionary *errorDict = [errors objectAtIndex:0];
                if ([errorDict objectForKey:@"ErrorCode"]) {
                    [retDict setObject:[errorDict objectForKey:@"ErrorCode"] forKey:@"errorCode"];
                }
                if ([errorDict objectForKey:@"Message"])
                {
                    NSArray *msgArr = [[errorDict objectForKey:@"Message"] componentsSeparatedByString:@"|"];
                    if (msgArr.count>1)
                    {
                        NSString *msgStr = [msgArr lastObject];
                        if (msgStr)
                        {
                            [retDict setObject:msgStr forKey:@"errorInfo"];
                        }
                    }
                    else{
                        [retDict setObject:@"请求失败" forKey:@"errorInfo"];
                    }
                }
            }
        }
    }
    
    return retDict;
}

//生成请求参数
+ (NSMutableDictionary *)createRequestParamsWithBodyParams:(NSDictionary *)bodyParams
{
    NSMutableDictionary *headerParams=[RequestHelper createRequestHeaderParams];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:1];
    if (headerParams) {
        [params setObject:headerParams forKey:@"requestHead"];
    }
    if (bodyParams) {
        [params setObject:bodyParams forKey:@"body"];
    }
    
    return params;
}

//获取网络请求错误信息
+ (NSString *)getRequestErrorInfo:(NSDictionary *)retDict
{
    NSDictionary *statusDict = [retDict objectForKey:@"ResponseStatus"];
    if (statusDict) {
        NSArray *errors = [statusDict objectForKey:@"Errors"];
        if (errors.count>0) {
            NSDictionary *errorDict = [errors objectAtIndex:0];
            if ([errorDict objectForKey:@"Message"])
            {
                NSArray *msgArr = [[errorDict objectForKey:@"Message"] componentsSeparatedByString:@"|"];
                if (msgArr.count>1)
                {
                    NSString *msgStr = [msgArr lastObject];
                    return msgStr;
                }
            }
        }
    }
    
    return nil;
}

//提示错误信息
+ (void)showRequestErrorInfo:(NSString *)errorMsg
{
    if (errorMsg) {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:errorMsg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertView show];
        
        UIView *view = [[UIApplication sharedApplication].delegate window];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
        hud.userInteractionEnabled = NO;
        hud.mode = MBProgressHUDModeText;
        hud.detailsLabelText = errorMsg;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:2];
    }
}

//提示网络错误，请稍后再试
+ (void)showRequestNetWorkError
{
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常，请稍后再试" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [alertView show];
    
    UIView *view = [[UIApplication sharedApplication].delegate window];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.userInteractionEnabled = NO;
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabelText = @"网络异常，请稍后再试";
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2];
}

@end
